/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nhadat.dao;

import java.util.List;
import nhadat.entity.TblLoaiTin;
import nhadat.hibernate.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Xe Bay + DUNGND60190
 */
public class LoaiTinDAO {

    private Session session;

    public LoaiTinDAO() {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

//    public static void main(String[] args) {
//        LoaiTinDAO test = new LoaiTinDAO();
//        String value = test.getMaLoaiNhaByTenLoaiGiayto("Cần Bán");
//        System.out.println(value);
//    }

    public String getMaLoaiNhaByTenLoaiGiayto(String tenloaitin) {
        Transaction trans = null;
        try {
            trans = session.getTransaction();
            trans.begin();
            String sql = "select maloaitin from TblLoaiTin where tenloaitin = ?";
            Query query = session.createQuery(sql);
            query.setString(0, tenloaitin);

            String maloaitin = query.uniqueResult().toString();

            session.flush();
            trans.commit();
            if (!maloaitin.isEmpty()) {
                return maloaitin;
            }
        } catch (Exception e) {
            if (trans.isActive()) {
                trans.rollback();
            }
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return null;
    }

    public TblLoaiTin[] getAllLoaiTin() {
        Transaction trans = null;
        try {
            trans = session.getTransaction();
            trans.begin();
            String sql = "From TblLoaiTin";
            Query query = session.createQuery(sql);

            List result = query.list();

            TblLoaiTin[] dsLoaiTin = new TblLoaiTin[result.size()];
            result.toArray(dsLoaiTin);

            session.flush();
            trans.commit();

            return dsLoaiTin;
        } catch (Exception e) {
            if (trans.isActive()) {
                trans.rollback();
            }
            // e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return null;
    }
}
